package api

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"week2/global"
	"week2/internal/models/dao"
	"week2/internal/models/services"
	"week2/internal/request"
	"week2/pkg"
)

func Register(c *gin.Context) {
	var req request.RegisterReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "数据不能为空",
		})
		return
	}

	user := dao.User{
		Mobile: req.Mobile,
	}
	if !pkg.ValidateMobile(req.Mobile) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "手机号格式错误",
		})
		return
	}
	err = services.CreateUser(user)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "注册失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "注册成功",
		})
	}
}

func Send(c *gin.Context) {
	var req request.SendReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "数据不能为空",
		})
		return
	}
	code := rand.Intn(9999) + 1000
	key := services.GetMobile(req.Mobile)
	global.RedisClient.Set(key, code, time.Minute*30)
	err = pkg.SendSms(req.Mobile, strconv.Itoa(code))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "短信发送失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "短信发送成功",
		})
	}
}

func Login(c *gin.Context) {
	var req request.LoginReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "数据不能为空",
		})
		return
	}
	res, _ := services.GetUserInfo(req.Mobile)

	key := services.GetMobile(req.Mobile)
	global.RedisClient.Get(key).Val()
	CustomClaims := pkg.CustomClaims{
		ID: res.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	}
	token, err := pkg.NewJWT("2209A").CreateToken(CustomClaims)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "登录失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "登录成功",
			"data": token,
		})
	}
}
